#!/usr/bin/env python3
"""
测试 Python 调用 Android API 的脚本

使用方法:
    python test_python_api.py
"""

import subprocess
import sys
import time
import shutil

def test_broadcast():
    """测试发送广播"""
    print("=" * 60)
    print("测试 Python 调用 Android API")
    print("=" * 60)

    # 确保应用已启动
#     print("\n0. 确保 Termux 应用已启动...")
#     subprocess.run(["am", "start", "-n", "com.termux/.app.TermuxActivity"],
#                    capture_output=True)
#     time.sleep(0.5)  # 等待应用启动

    # 检查 am 命令是否可用
    am_path = shutil.which("am")
    if not am_path:
        print("❌ am 命令未找到！")
        print("\n请安装 termux-tools:")
        print("  pkg install termux-tools")
        print("\n然后重新运行此脚本")
        return
    
    # 测试 am 命令是否能正常工作（实际测试广播功能）
    print(f"ℹ️  am 命令路径: {am_path}")
    print("   测试 am broadcast 功能...")
    # 尝试发送一个测试广播（使用不存在的 action，只测试命令本身）
    test_result = subprocess.run(
        ["am", "broadcast", "-a", "com.termux.TEST"],
        capture_output=True,
        text=True,
        timeout=3
    )
    # 如果返回码是 0 或 255，或者输出包含 broadcast/Intent 相关，说明命令可用
    if test_result.returncode in [0, 255] or any(keyword in (test_result.stdout + test_result.stderr).lower() 
                                                  for keyword in ["broadcast", "intent", "component"]):
        print("   ✓ am broadcast 命令可用")
    elif "command not found" in test_result.stderr.lower() or "command not found" in test_result.stdout.lower():
        print("❌ am 命令无法执行")
        print("\n请安装 termux-tools:")
        print("  pkg install termux-tools")
        print("\n然后重新运行此脚本")
        return
    else:
        print("⚠️  警告: am 命令可能功能不完整")
        print("   Termux bootstrap 的 am 命令可能无法发送广播")
        print("   建议安装 termux-tools 以确保完整功能:")
        print("     pkg install termux-tools")
    
    # 测试 1: 显示 Toast（使用显式组件名）
    print("\n1. 测试显示 Toast（显式组件）...")
    cmd = [
        "am", "broadcast",
        "-a", "com.termux.PYTHON_API",
        "-n", "com.termux/.app.api.PythonApiReceiver",
        "--es", "action", "show_toast",
        "--es", "message", "Hello from Python! 测试消息"
    ]
    print(f"执行命令: {' '.join(cmd)}")
    result = subprocess.run(cmd, capture_output=True, text=True)
    print(f"返回码: {result.returncode}")
    
    if result.returncode == -6:
        print("❌ 返回码 -6")
        print("\n可能的原因:")
        print("1. PythonApiReceiver 组件不存在（需要重新编译安装应用）")
        print("2. 应用未运行")
        print("3. am 命令问题（通常 Termux bootstrap 已包含）")
    
    if result.stdout:
        print(f"输出: {result.stdout}")
    if result.stderr:
        print(f"错误: {result.stderr}")

    # 测试 1b: 显示 Toast（再次测试，确保应用已启动）
    print("\n1b. 再次测试显示 Toast...")
    cmd = [
        "am", "broadcast",
        "-a", "com.termux.PYTHON_API",
        "-n", "com.termux/.app.api.PythonApiReceiver",
        "--es", "action", "show_toast",
        "--es", "message", "第二次测试消息"
    ]
    print(f"执行命令: {' '.join(cmd)}")
    result = subprocess.run(cmd, capture_output=True, text=True)
    print(f"返回码: {result.returncode}")
    if result.stdout:
        print(f"输出: {result.stdout}")
    if result.stderr:
        print(f"错误: {result.stderr}")

    # 测试 2: 发送通知
    print("\n2. 测试发送通知...")
    cmd = [
        "am", "broadcast",
        "-a", "com.termux.PYTHON_API",
        "-n", "com.termux/.app.api.PythonApiReceiver",
        "--es", "action", "notification",
        "--es", "title", "Python 测试通知",
        "--es", "message", "这是一条来自 Python 的测试通知"
    ]
    print(f"执行命令: {' '.join(cmd)}")
    result = subprocess.run(cmd, capture_output=True, text=True)
    print(f"返回码: {result.returncode}")
    if result.stdout:
        print(f"输出: {result.stdout}")
    if result.stderr:
        print(f"错误: {result.stderr}")

    # 测试 3: 显示对话框（实际是通知）
    print("\n3. 测试显示对话框（通过通知）...")
    cmd = [
        "am", "broadcast",
        "-a", "com.termux.PYTHON_API",
        "-n", "com.termux/.app.api.PythonApiReceiver",
        "--es", "action", "show_dialog",
        "--es", "title", "Python 对话框",
        "--es", "message", "这是对话框内容"
    ]
    print(f"执行命令: {' '.join(cmd)}")
    result = subprocess.run(cmd, capture_output=True, text=True)
    print(f"返回码: {result.returncode}")
    if result.stdout:
        print(f"输出: {result.stdout}")
    if result.stderr:
        print(f"错误: {result.stderr}")

    # 测试 4: 自动查看日志
    print("\n4. 查看 PythonApiReceiver 日志...")
    print("-" * 60)
    time.sleep(0.5)  # 等待广播被处理

    # 查看日志
    result = subprocess.run(
        ["logcat", "-d", "-s", "PythonApiReceiver:*"],
        capture_output=True,
        text=True
    )

    if result.stdout and "PythonApiReceiver" in result.stdout:
        print("✓ 找到 PythonApiReceiver 日志:")
        lines = result.stdout.strip().split('\n')
        # 显示最后10行相关日志
        for line in lines[-10:]:
            if "PythonApiReceiver" in line:
                print(f"  {line}")
    else:
        print("⚠️  没有找到 PythonApiReceiver 的日志")
        print("\n可能的原因:")
        print("1. BroadcastReceiver 没有收到广播")
        print("2. 需要重新编译并安装应用")
        print("3. 日志级别设置问题")
        print("\n手动查看日志:")
        print("  logcat -d | grep PythonApiReceiver")

    print("\n" + "=" * 60)
    print("测试完成！")
    print("=" * 60)
    print("\n检查结果:")
    print("1. 如果看到了 Toast 消息 → BroadcastReceiver 工作正常 ✓")
    print("2. 如果看到了通知 → BroadcastReceiver 工作正常 ✓")
    print("3. 如果看到了日志 → BroadcastReceiver 收到了广播 ✓")
    print("4. 如果都没有 → 请重新编译安装应用并确保应用已启动")
    
    print("\n按 Enter 键退出...")
    try:
        input()
    except (EOFError, KeyboardInterrupt):
        pass

if __name__ == "__main__":
    test_broadcast()

